package rabbitmq.direct;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import rabbitmq.constants.Constants;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1.建立连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setUsername(Constants.USERNAME);
        factory.setPassword(Constants.PASSWORD);
        factory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = factory.newConnection();
        // 2.创建信道
        Channel channel = connection.createChannel();
        // 3.声明交换机
        channel.exchangeDeclare(Constants.DIRECT_EXCHANGE, BuiltinExchangeType.DIRECT,true,false,false,null);
        // 4.声明队列
        channel.queueDeclare(Constants.DIRECT_QUEUE1,true,false,false,null);
        channel.queueDeclare(Constants.DIRECT_QUEUE2,true,false,false,null);
        // 5.关联交换机
        channel.queueBind(Constants.DIRECT_QUEUE1,Constants.DIRECT_EXCHANGE,"a",null);
        channel.queueBind(Constants.DIRECT_QUEUE2,Constants.DIRECT_EXCHANGE,"a",null);
        channel.queueBind(Constants.DIRECT_QUEUE2,Constants.DIRECT_EXCHANGE,"b",null);
        channel.queueBind(Constants.DIRECT_QUEUE2,Constants.DIRECT_EXCHANGE,"c",null);
        // 6.发送消息
        String msg = "hello direct, my routingKey is a...";
        channel.basicPublish(Constants.DIRECT_EXCHANGE,"a",null,msg.getBytes());

        msg = "hello direct, my routingKey is b...";
        channel.basicPublish(Constants.DIRECT_EXCHANGE,"b",null,msg.getBytes());

        msg = "hello direct, my routingKey is c...";
        channel.basicPublish(Constants.DIRECT_EXCHANGE,"c",null,msg.getBytes());

        // 7.释放资源
        channel.close();
        connection.close();

        System.out.println("消息发送完毕~");
    }
}
